using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;

[Serializable]
public class ObjectRecycler
{
	public ObjectRecycler()
	{
		this.Init();
	}

	public ObjectRecycler(GameObject go, int totalObjectsAtStart)
	{
		this.Init(go, totalObjectsAtStart, null);
	}

	//[DebuggerBrowsable(DebuggerBrowsableState.Never)]
	public event ObjectRecycler.ObjectRecuyclerChangedEventHandler onObjectRecyclerChanged;

	public void Init()
	{
		this.Init(this.parent);
	}

	public void Init(GameObject parent)
	{
		this.Init(this.objectToRecycle, this.totalObjectsAtStart, parent);
	}

	public void Init(GameObject go, int totalObjectsAtStart, GameObject parent)
	{
		this.objectList = new List<GameObject>();
		this.objectToRecycle = go;
		this.parent = parent;
		for (int i = 0; i < totalObjectsAtStart; i++)
		{
			GameObject gameObject = UnityEngine.Object.Instantiate<GameObject>(go);
			if (null != parent)
			{
				gameObject.transform.parent = parent.transform;
			}
			gameObject.SetActive(false);
			this.objectList.Add(gameObject);
		}
	}

	private void fireRecycledEvent()
	{
		if (this.onObjectRecyclerChanged != null)
		{
			IEnumerable<GameObject> source = from item in this.objectList
			where !item.activeSelf
			select item;
			this.onObjectRecyclerChanged(source.Count<GameObject>(), this.objectList.Count);
		}
	}

	public GameObject nextFree
	{
		get
		{
			GameObject gameObject = (from item in this.objectList
			where !item.activeSelf
			select item).FirstOrDefault<GameObject>();
			if (gameObject == null)
			{
				gameObject = UnityEngine.Object.Instantiate<GameObject>(this.objectToRecycle);
				if (null != this.parent)
				{
					gameObject.transform.parent = this.parent.transform;
				}
				this.objectList.Add(gameObject);
			}
			gameObject.SetActive(true);
			this.fireRecycledEvent();
			return gameObject;
		}
	}

	public void freeObject(GameObject objectToFree)
	{
		objectToFree.SetActive(false);
		this.fireRecycledEvent();
	}

	public void freeAll()
	{
		for (int i = 0; i < this.objectList.Count; i++)
		{
			this.objectList[i].gameObject.SetActive(false);
		}
	}

	private List<GameObject> objectList;

	public GameObject parent;

	public GameObject objectToRecycle;

	public int totalObjectsAtStart;

	public delegate void ObjectRecuyclerChangedEventHandler(int available, int total);
}
